package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.EnrollList;
import com.xmy.cultivate.entity.views.FirstSignUp;
import com.xmy.cultivate.entity.views.IncomeDayReport;
import com.xmy.cultivate.entity.views.ResApplyGather;
import com.xmy.cultivate.enums.OrderTypeEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusOrderApplyEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.IncomeDailyRs;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.ConfigData;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.ResultCode;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单报名信息 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-01
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements IOrderDetailService {


    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    CourseMapper courseMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    StaffMapper staffMapper;

    @Autowired
    @Lazy
    OrganizationMapper organizationMapper;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    SubjectsMapper subjectsMapper;

    @Autowired
    @Lazy
    IStudentTypeService iStudentTypeService;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    EnrollInfoMapper enrollInfoMapper;

    @Autowired
    @Lazy
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    ICoursePricingService iCoursePricingService;

    @Autowired
    @Lazy
    IOrderDisDetailService iOrderDisDetailService;

    @Autowired
    @Lazy
    IOrderApplyAffirmService iOrderApplyAffirmService;

    @Autowired
    @Lazy
    OrderCoursePricingMapper orderCoursePricingMapper;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    IOrderDisClanService iOrderDisClanService;

    public IPage<EnrollList> getEnrollList(IPage<?> page, Wrapper wrapper) {
        IPage<EnrollList> enrollListIPage = orderDetailMapper.getEnrollList(page, wrapper);
        for (EnrollList enrollList : enrollListIPage.getRecords()) {
            Course course = courseMapper.selectById(enrollList.getCourseId());
            if (course != null) {
                enrollList.setSubjectsId(course.getSubjectsId());
                //System.out.print("---"+enrollList.getSchoolId()+"="+enrollList.getStudentId()+"="+course.getId());
                boolean isNew = iStudentTypeService.isNew(enrollList.getSchoolId(), enrollList.getStudentId(), course.getSubjectsId());
                if (isNew) {
                    enrollList.setIsNewStudent(1);
                } else {
                    enrollList.setIsNewStudent(2);
                }
            }
        }

        return enrollListIPage;
    }

    public Map<String, BigDecimal> enrollListMoney(Wrapper wrapper) {
        BigDecimal solidPrice = orderDetailMapper.getSolidPrice(wrapper);
        BigDecimal studentCount = orderDetailMapper.getAllStudentCount(wrapper);

        Map<String, BigDecimal> map = new HashMap<>();
        map.put("solidPrice", solidPrice);
        map.put("studentCount", studentCount);
        return map;
    }


    public List<OrderDetail> orderDetail(Wrapper wrapper) {
        return orderDetailMapper.orderDetail(wrapper);
    }

    public Integer getApplyCountForSubjects(Long schoolId, Long studentId, Long subjectsId, Integer newYeartPart, Integer newNum, Integer lessonType) {
        return orderDetailMapper.getApplyCountForSubjects(schoolId, studentId, subjectsId, newYeartPart, newNum, lessonType);
    }

    public OrderDetail getLastOneForStudent(Long schoolId, Long studentId, Long subjectsId, Integer yearPart, Integer quarterNum, Integer lessonType) {
        return orderDetailMapper.getLastOneForSubjectId(schoolId, studentId, subjectsId, yearPart, quarterNum, lessonType);
    }

    /**
     * 办理中心获取学员报读信息
     *
     * @return
     */
    public List<OrderDetail> GetLessonByStuInfoId(Wrapper wrapper) {
        return orderDetailMapper.GetLessonByStuInfoId(wrapper);
    }

    public List<Subjects> GetSubjectsByStuInfoId(Wrapper wrapper) {

        List<Subjects> subjectsList = orderDetailMapper.GetSubjectsByStuInfoId(wrapper);
        for (Subjects subjects : subjectsList) {
            Organization organization = organizationMapper.selectById(subjects.getSchoolId());
            Course course = courseMapper.selectById(subjects.getCourseId());
            if (organization != null) {
                subjects.setSchoolName(organization.getName());
                if (course != null) {
                    subjects.setYearClassId(course.getYearClassId().getKey());
                }
            }
        }
        return subjectsList;
    }

    public List<OrderDetail> getLessonByCourseId(Long courseId, Long studentId, Long schoolId) {
        List<OrderDetail> orderDetailList = orderDetailMapper.getLessonByCourseId(courseId, studentId, schoolId);
        return orderDetailList;
    }

    @Override
    public Integer getAllCourseCountForSubjects(Long schoolId, Long studentId, Long subjectsId, Integer yearAndQuarter, Integer lessonType) {
        return orderDetailMapper.getAllCourseCountForSubjects(schoolId, studentId, subjectsId, yearAndQuarter, lessonType);
    }

    /**
     * 报读通过科目，获取在读信息
     *
     * @param subjectsId
     * @param studentId
     * @return
     */
    public List<OrderDetail> getLessonForSubjects(Long subjectsId, Long studentId, Long schoolId, Integer lessonType) {
        List<OrderDetail> orderDetailList = orderDetailMapper.getLessonForSubjects(subjectsId, studentId, schoolId, lessonType);
        for (OrderDetail orderDetail : orderDetailList) {
            OrderCoursePricing orderCoursePricing = orderCoursePricingMapper.selectById(orderDetail.getId());
            CoursePricing coursePricing = new CoursePricing();
            if (orderCoursePricing == null) {
                coursePricing = iCoursePricingService.getCoursePricingByCourseId(orderDetail.getCourseId(), schoolId, 3);
            } else {
                BeanUtils.copyProperties(orderCoursePricing, coursePricing);
            }
            orderDetail.setCoursePricingModel(coursePricing);

        }
        return orderDetailList;
    }

    public List<Organization> getSignUpSchoolListForWhere(@Param(Constants.WRAPPER) Wrapper wrapper) {
        return orderDetailMapper.getSignUpSchoolListForWhere(wrapper);
    }

    public FirstSignUp getFirstSignUp(Long studentId, Long gradeId, Integer count) {
        return orderDetailMapper.getFirstSignUp(studentId, gradeId, count);
    }

    public Boolean stopCourse(Long orderDetailId) {

        OrderDetail orderDetail = orderDetailMapper.selectById(orderDetailId);
        if (orderDetail == null) {
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        }

        if (orderDetail.getReadingStatus() != ReadingStatusEnum.IN_READING) {
            throw new CommonException(ResultCode.STATUSNOT);
        }
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id", orderDetail.getOrderId()).ne("status", 2);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailQueryWrapper);


        for (OrderDetail orderDetailTemp : orderDetailList) {

        }
        return true;
    }

    public IPage<IncomeDayReport> getIncomeDayReport(IPage<?> page, Wrapper wrapper, Integer readType, String payNum) {
        IPage<IncomeDayReport> iPage = orderDetailMapper.getIncomeDayReport(page, wrapper, readType, payNum);
        for (IncomeDayReport incomeDayReport : iPage.getRecords()) {
            if (incomeDayReport.getGradeId() != null) {
                Grade grade = gradeMapper.selectById(incomeDayReport.getGradeId());
                Course course = courseMapper.selectById(incomeDayReport.getCourseId());
                if (grade != null) {
                    incomeDayReport.setGradeName(grade.getName());
                    Staff staff = staffMapper.selectById(grade.getTeacherId());
                    if (staff != null) {
                        incomeDayReport.setTeacherName(staff.getName());
                    }
                }
                if (course != null) {
                    incomeDayReport.setSubjectsName(ConfigData.getSubjectsNameForNum(Integer.parseInt(course.getSubjectsId().toString())));
                }
            }
            if (incomeDayReport.getAffirmTypeList().contains(2)) {
                incomeDayReport.setArriveAffirm(2);
            }

            QueryWrapper<OrderDisDetail> orderDisDetailQueryWrapper = new QueryWrapper<>();
            orderDisDetailQueryWrapper.eq("order_id", incomeDayReport.getOrderId());
            //orderDisDetailQueryWrapper.eq("order_id",incomeDayReport.getOrderId());
            List<OrderDisDetail> orderDisDetailList = iOrderDisDetailService.list(orderDisDetailQueryWrapper);
            for (OrderDisDetail orderDisDetail : orderDisDetailList) {
                String clanName = iOrderDisClanService.getClanName(incomeDayReport.getStudentId());
                if (StringUtils.isNotBlank(clanName)) {
                    orderDisDetail.setClanName(clanName);
                }
            }
            incomeDayReport.setOrderDisDetailList(orderDisDetailList);

            //<OrderApplyAffirm> orderApplyAffirmQueryWrapper = new QueryWrapper<>();
            //orderApplyAffirmQueryWrapper.eq("order_id",incomeDayReport.getOrderId());
            //orderApplyAffirmQueryWrapper.eq("affirm_type",2);
            //orderApplyAffirmQueryWrapper.eq("type",2);
            //Long count = iOrderApplyAffirmService.count(orderApplyAffirmQueryWrapper);
            if (incomeDayReport.getArriveAffirm().equals(2)) {
                incomeDayReport.setIsAffirmDis(1);
            } else {
                incomeDayReport.setIsAffirmDis(0);
            }


            /**
             * 邀约人
             */
            List<String> inviteNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(), 1);
            /**
             * 试听人
             */
            List<String> auditionNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(), 2);
            /**
             * 成交人
             */
            List<String> bargainNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(), 3);

            incomeDayReport.setInviteNames(String.join(",", inviteNameList));
            incomeDayReport.setAuditionNames(String.join(",", auditionNameList));
            incomeDayReport.setBargainNames(String.join(",", bargainNameList));

            Course course = courseMapper.selectById(incomeDayReport.getCourseId());
            incomeDayReport.setYearClassName(ConfigData.getYearClassForNum(course.getYearClassId().getKey()));
        }

        return iPage;
    }


    @Override
    public IPage<IncomeDayReport> getDisList(IPage<?> page,
                                             Integer yearPart,
                                             Integer quarterNum,
                                             List<Long> schoolIdList,
                                             String subjectsId,
                                             String status,
                                             String studentName,
                                             String lessonType,
                                             List<Integer> yearClassIdList,
                                             String handlePersonId,
                                             String startDate,
                                             String endDate,
                                             String orderType,
                                             String payeeId,
                                             String inviteId,
                                             String teacherId
    ) {

        IPage<IncomeDayReport> iPage = orderDetailMapper.getDisList(page, yearPart, quarterNum, schoolIdList, subjectsId, status, studentName, lessonType, yearClassIdList, handlePersonId, startDate, endDate, orderType, payeeId, inviteId, teacherId);
        for (IncomeDayReport incomeDayReport : iPage.getRecords()) {
            if (incomeDayReport.getGradeId() != null) {
                Grade grade = gradeMapper.selectById(incomeDayReport.getGradeId());
                Course course = courseMapper.selectById(incomeDayReport.getCourseId());
                if (grade != null) {
                    incomeDayReport.setGradeName(grade.getName());
                    Staff staff = staffMapper.selectById(grade.getTeacherId());
                    if (staff != null) {
                        incomeDayReport.setTeacherName(staff.getName());
                    }
                }
                if (course != null) {
                    incomeDayReport.setSubjectsName(ConfigData.getSubjectsNameForNum(Integer.parseInt(course.getSubjectsId().toString())));
                }
            }
            if (incomeDayReport.getAffirmTypeList().contains(2)) {
                incomeDayReport.setArriveAffirm(2);
            }

            //收款人
            Staff payee = staffMapper.selectById(incomeDayReport.getPayeeId());
            if (payee != null) {
                incomeDayReport.setPayeeName(payee.getName());
            }

            QueryWrapper<OrderDisDetail> orderDisDetailQueryWrapper = new QueryWrapper<>();
            orderDisDetailQueryWrapper.eq("order_id", incomeDayReport.getOrderId());
            orderDisDetailQueryWrapper.and(i -> i.eq("dis_price_id", incomeDayReport.getId()).or().eq("dis_price_id", 0));
            //orderDisDetailQueryWrapper.eq("order_id",incomeDayReport.getOrderId());
            List<OrderDisDetail> orderDisDetailList = iOrderDisDetailService.list(orderDisDetailQueryWrapper);
            for (OrderDisDetail orderDisDetail : orderDisDetailList) {
                String clanName = iOrderDisClanService.getClanName(incomeDayReport.getStudentId());
                if (StringUtils.isNotBlank(clanName)) {
                    orderDisDetail.setClanName(clanName);
                }
            }
            incomeDayReport.setOrderDisDetailList(orderDisDetailList);

            //<OrderApplyAffirm> orderApplyAffirmQueryWrapper = new QueryWrapper<>();
            //orderApplyAffirmQueryWrapper.eq("order_id",incomeDayReport.getOrderId());
            //orderApplyAffirmQueryWrapper.eq("affirm_type",2);
            //orderApplyAffirmQueryWrapper.eq("type",2);
            //Long count = iOrderApplyAffirmService.count(orderApplyAffirmQueryWrapper);

            //优惠状态调整
            /*if (incomeDayReport.getArriveAffirm().equals(2)){
                incomeDayReport.setIsAffirmDis(1);
            }else {
                incomeDayReport.setIsAffirmDis(0);
            }*/
            incomeDayReport.setIsAffirmDis(incomeDayReport.getStatus());

            /**
             * 邀约人
             */
            List<String> inviteNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(), 1);
            /**
             * 试听人
             */
            List<String> auditionNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(), 2);
            /**
             * 成交人
             */
            List<String> bargainNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(), 3);

            incomeDayReport.setInviteNames(String.join(",", inviteNameList));
            incomeDayReport.setAuditionNames(String.join(",", auditionNameList));
            incomeDayReport.setBargainNames(String.join(",", bargainNameList));

            Course course = courseMapper.selectById(incomeDayReport.getCourseId());
            incomeDayReport.setYearClassName(ConfigData.getYearClassForNum(course.getYearClassId().getKey()));
        }

        return iPage;
    }


    @Override
    public BigDecimal getDisPrice(
            Integer yearPart,
            Integer quarterNum,
            List<Long> schoolIdList,
            String subjectsId,
            String status,
            String studentName,
            String lessonType,
            List<Integer> yearClassIdList,
            String handlePersonId,
            String startDate,
            String endDate,
            String orderType,
            String payeeId,
            String inviteId,
            String teacherId
    ) {
        return orderDetailMapper.getDisPrice(yearPart, quarterNum, schoolIdList, subjectsId, status, studentName, lessonType, yearClassIdList, handlePersonId, startDate, endDate, orderType,payeeId, inviteId, teacherId);
    }


    /**
     * 获取实收金额
     *
     * @param wrapper
     * @return
     */
    public BigDecimal getSolidStatisticsPrice(Wrapper wrapper) {
        return orderDetailMapper.getSolidStatisticsPrice(wrapper);
    }

    @Override
    public BigDecimal getStatisticsPrice(Wrapper wrapper) {
        return orderDetailMapper.getStatisticsPrice(wrapper);
    }


    public IPage<ResApplyGather> applyGatherForPage(Wrapper wrapper, IPage<OrderDetail> page) {
        IPage<ResApplyGather> orderDetailIPage = orderDetailMapper.getOrderDetailListForPage(page, wrapper);

        for (ResApplyGather resApplyGather : orderDetailIPage.getRecords()) {
            Organization schoolInfo = organizationMapper.selectById(resApplyGather.getSchoolId());
            if (schoolInfo != null) {
                resApplyGather.setSchoolName(schoolInfo.getName());
            }

            Student studentInfo = studentMapper.selectById(resApplyGather.getStudentId());
            if (studentInfo != null) {
                resApplyGather.setStudentName(studentInfo.getName());
            }

            Subjects subjectsInfo = subjectsMapper.selectById(resApplyGather.getSubjectsId());
            if (subjectsInfo != null) {
                resApplyGather.setSubjectsName(subjectsInfo.getName());
            }
            BigDecimal allSolidPrice = orderDetailMapper.getAllSolidPrice(resApplyGather.getSchoolId(), resApplyGather.getStudentId(), resApplyGather.getSubjectsId(), resApplyGather.getLessonType());

            Integer allCourseHouse = orderDetailMapper.getAllCouseHouse(resApplyGather.getSchoolId(), resApplyGather.getStudentId(), resApplyGather.getSubjectsId(), resApplyGather.getYearPart(), resApplyGather.getQuarterNum(), resApplyGather.getLessonType());

            Integer yearPartAndQurarter = Integer.parseInt(resApplyGather.getYearPart() + "" + resApplyGather.getQuarterNum());
            Integer allResidueCourseHouse = orderDetailMapper.getResidueCourseCountForSubjects(resApplyGather.getSchoolId(), resApplyGather.getStudentId(), resApplyGather.getSubjectsId(), yearPartAndQurarter, resApplyGather.getLessonType());

            Integer allUseCourseHouse = studentGradeMapper.getStudentGradeUseCount(resApplyGather.getSchoolId(), resApplyGather.getStudentId(), resApplyGather.getSubjectsId());

            resApplyGather.setAllSolidPrice(allSolidPrice);
            resApplyGather.setResidueCourseHouse(allResidueCourseHouse);
            resApplyGather.setAllCourseHouse(allCourseHouse);
            resApplyGather.setAllUseCourseHouse(allUseCourseHouse);
        }

        return orderDetailIPage;
    }

    public List<ResApplyGather> applyGatherList(Wrapper wrapper) {
        List<ResApplyGather> resApplyGatherList = orderDetailMapper.getOrderDetailList(wrapper);

        for (ResApplyGather resApplyGather : resApplyGatherList) {
            Organization schoolInfo = organizationMapper.selectById(resApplyGather.getSchoolId());
            if (schoolInfo != null) {
                resApplyGather.setSchoolName(schoolInfo.getName());
            }

            Student studentInfo = studentMapper.selectById(resApplyGather.getStudentId());
            if (studentInfo != null) {
                resApplyGather.setStudentName(studentInfo.getName());
            }

            Subjects subjectsInfo = subjectsMapper.selectById(resApplyGather.getSubjectsId());
            if (subjectsInfo != null) {
                resApplyGather.setSubjectsName(subjectsInfo.getName());
            }
            BigDecimal allSolidPrice = orderDetailMapper.getAllSolidPrice(resApplyGather.getSchoolId(), resApplyGather.getStudentId(), resApplyGather.getSubjectsId(), resApplyGather.getLessonType());

            Integer allCourseHouse = orderDetailMapper.getAllCouseHouse(resApplyGather.getSchoolId(), resApplyGather.getStudentId(), resApplyGather.getSubjectsId(), resApplyGather.getYearPart(), resApplyGather.getQuarterNum(), resApplyGather.getLessonType());

            Integer yearPartAndQuarter = Integer.parseInt(resApplyGather.getYearPart() + "" + resApplyGather.getQuarterNum());

            Integer allResidueCourseHouse = orderDetailMapper.getResidueCourseCountForSubjects(resApplyGather.getSchoolId(), resApplyGather.getStudentId(), resApplyGather.getSubjectsId(), yearPartAndQuarter, resApplyGather.getLessonType());

            Integer allUseCourseHouse = studentGradeMapper.getStudentGradeUseCount(resApplyGather.getSchoolId(), resApplyGather.getStudentId(), resApplyGather.getSubjectsId());

            resApplyGather.setAllSolidPrice(allSolidPrice);
            resApplyGather.setResidueCourseHouse(allResidueCourseHouse);
            resApplyGather.setAllCourseHouse(allCourseHouse);
            resApplyGather.setAllUseCourseHouse(allUseCourseHouse);
        }

        return resApplyGatherList;
    }

    public List<OrderDetail> getBigFifteeList() {
        return orderDetailMapper.getBigFifteeList();
    }

    public Integer getUseCourseHouse(Wrapper wrapper) {
        return orderDetailMapper.getUseCourseHouse(wrapper);
    }

    @Override
    public BigDecimal getAllResiduePrice(Long schoolId, Long studentId, Long subjectsId, Integer yearAndQuarter, Integer lessonType) {
        return orderDetailMapper.getAllResiduePrice(schoolId, studentId, subjectsId, yearAndQuarter, lessonType);
    }

    public Integer getResidueCourseCount(Long schoolId, Long studentId, Long subjectsId, Integer yearAndQuarter, Integer lessonType) {
        return orderDetailMapper.getResidueCourseCount(schoolId, studentId, subjectsId, yearAndQuarter, lessonType);
    }


    /**
     * 获取剩余课时大于0的订单，初始化班型用
     *
     * @return
     */
    @Override
    public List<OrderDetail> getOrderDetailForResidueCoruseCount() {
        return orderDetailMapper.getOrderDetailForResidueCoruseCount();
    }

    /**
     * 获取剩余课时大于0的各科目数据
     *
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @param lessonType
     * @param studentId
     * @return
     */
    public List<OrderDetail> getStudentOrderDetail(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Integer lessonType, Long studentId) {
        return orderDetailMapper.getStudentOrderDetail(yearPart, quarterNum, schoolId, subjectsId, lessonType, studentId);
    }

    /**
     * 智能课，刷题班自动报名
     *
     * @return
     */
    @Override
    @Async("onlineAsync")
    public void addOrderApply(Integer yearPart, Integer quarterNum, Long schoolId, Long subjectsId, Integer lessonType, Long studentId) {
        List<OrderDetail> orderDetailList = this.getStudentOrderDetail(yearPart, quarterNum, schoolId, subjectsId, lessonType, studentId);

        LocalDate localDateNow = LocalDate.now();
        Integer i = 1;
        for (OrderDetail orderDetail : orderDetailList) {
            //System.out.println("count:"+orderDetailList.size()+"i:"+i);
            try {
                i++;
                OrderDetail orderDetailItem = null;
                Integer lessonTypeInsert = null;
                if (orderDetail.getSubjectsId().equals(1L)) {
                    lessonTypeInsert = 2;
                } else if (orderDetail.getSubjectsId().equals(2L) || orderDetail.getSubjectsId().equals(3L)) {
                    lessonTypeInsert = 3;
                }
                QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
                wrapper.eq("year_part", orderDetail.getYearPart());
                wrapper.eq("quarter_num", orderDetail.getQuarterNum());
                wrapper.eq("subjects_id", orderDetail.getSubjectsId());
                wrapper.eq("lesson_type", lessonTypeInsert);
                wrapper.eq("student_id", studentId);
                wrapper.eq("school_id", schoolId);
                wrapper.ne("status", 2);
                wrapper.gt("residue_course_count", 0);
                Long count = orderDetailMapper.selectCount(wrapper);
                if (count > 0) {
                    continue;
                }
                Integer residueCourseCount = orderDetail.getResidueCourseCount() * 2;
                QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
                courseQueryWrapper.eq("lesson_type", lessonTypeInsert);
                courseQueryWrapper.eq("subjects_id", orderDetail.getSubjectsId());
                courseQueryWrapper.eq("status", 1);
                courseQueryWrapper.eq("quarter_num", quarterNum);
                courseQueryWrapper.last("limit 1");
                //courseQueryWrapper.eq();

                Course course = iCourseService.getOne(courseQueryWrapper);
                if (course == null) {
                    continue;
                }
                QueryWrapper<CoursePricing> coursePricingQueryWrapper = new QueryWrapper<>();
                if (course.getOpeningSchoolType().getKey().equals(1)) {
                    coursePricingQueryWrapper.inSql("price_school_id", "select id from course_price_school where course_id = " + course.getId() + " and school_id =0 and deleted=0");
                } else {
                    coursePricingQueryWrapper.inSql("price_school_id", "select id from course_price_school where course_id = " + course.getId() + " and school_id =" + orderDetail.getSchoolId() + " and deleted=0");

                }
                coursePricingQueryWrapper.last("limit 1");


                CoursePricing coursePricing = iCoursePricingService.getOne(coursePricingQueryWrapper);
                if (coursePricing == null) {
                    continue;
                }

                orderDetailItem = orderDetailMapper.getStudetnOrderDetailForLessonType(yearPart, quarterNum, orderDetail.getSchoolId(), orderDetail.getSubjectsId(), lessonTypeInsert, orderDetail.getStudentId());
                if (orderDetailItem == null) {
                    int[] randMath = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
                    Integer randReceiptNo = CommonUtil.getNotSimple(randMath, 7);

                    Long orderId = idWorker.nextId();
                    StringBuilder tradeContent = new StringBuilder();
                    tradeContent.append("报名：");
                    tradeContent.append(course.getName());
                    //tradeContent.append(",");
                    //tradeContent.append(residueCourseCount);
                    //tradeContent.append("课时");

                    OrderApply orderApply = new OrderApply();
                    orderApply.setId(orderId);
                    orderApply.setYearClassId(course.getYearClassId().getKey());
                    orderApply.setSubjectsIdStr(course.getSubjectsId().toString());
                    orderApply.setReceiptNo(randReceiptNo.toString());
                    orderApply.setLessonType(lessonTypeInsert);
                    orderApply.setPrice(new BigDecimal(0));
                    orderApply.setStudentId(orderDetail.getStudentId());
                    orderApply.setSchoolId(orderDetail.getSchoolId());
                    orderApply.setYearPart(yearPart);
                    orderApply.setQuarterNum(quarterNum);
                    orderApply.setHandleSchoolId(orderDetail.getSchoolId());
                    //orderApply.setHandleSchoolName();
                    orderApply.setHandleDate(localDateNow);
                    //orderApply.setHandlePersonId();
                    //orderApply.setHandlePersonName();
                    orderApply.setStatus(StatusOrderApplyEnum.NO);
                    orderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_SiGN);
                    orderApply.setTradeContent(tradeContent.toString());
                    iOrderApplyService.save(orderApply);


                    orderDetailItem = new OrderDetail();
                    orderDetailItem.setResidueCourseCount(residueCourseCount);
                    orderDetailItem.setId(idWorker.nextId());
                    orderDetailItem.setOrderId(orderId);
                    orderDetailItem.setSchoolId(orderDetail.getSchoolId());
                    orderDetailItem.setStudentId(orderDetail.getStudentId());
                    orderDetailItem.setLessonType(lessonTypeInsert);
                    orderDetailItem.setCourseId(course.getId());
                    orderDetailItem.setCourseName(course.getName());
                    orderDetailItem.setSubjectsId(orderDetail.getSubjectsId());
                    //orderDetailItem.setGradeId();
                    orderDetailItem.setCoursePriceId(coursePricing.getId());
                    orderDetailItem.setYearClassId(orderDetail.getYearClassId());
                    //orderDetailItem.setCount(residueCourseCount/coursePricing.getCount());
                    orderDetailItem.setAllCourseCount(residueCourseCount);
                    //orderDetailItem.setUseCourseCount();
                    orderDetailItem.setResidueCourseCount(residueCourseCount);
                    //orderDetailItem.setCourseHouse();
                    orderDetailItem.setUsePrice(new BigDecimal(0));
                    orderDetailItem.setEnrollType(1);
                    orderDetailItem.setHandleDate(localDateNow);
                    orderDetailItem.setYearPart(yearPart);
                    orderDetailItem.setQuarterNum(quarterNum);
                    orderDetailItem.setYearAndQuarter(Integer.parseInt(yearPart + "" + quarterNum));
                    orderDetailItem.setOrderType(OrderTypeEnum.ORDER_TYPE_SiGN);
                    orderDetailItem.setStatus(StatusOrderApplyEnum.NO);
                    orderDetailItem.setReadingStatus(ReadingStatusEnum.IN_READING);

                } else {
                    //BeanUtils.copyProperties(orderDetail,orderDetailItem);
                    orderDetailItem.setResidueCourseCount(residueCourseCount);

                }
                this.saveOrUpdate(orderDetailItem);
            } catch (Exception e) {
                //System.out.println(e);
                //log.error(e.toString());
            }
        }
    }

    @Override
    public List<OrderDetail> countStudentsBySubject() {
        return orderDetailMapper.countStudentsBySubject();
    }

    @Override
    public Integer countStudent() {
        return orderDetailMapper.studentCount();
    }

    @Override
    public List<OrderDetail> getTransferOrderDetail(Integer yearPart,
                                                    Integer quarterNum,
                                                    String schoolId,
                                                    Integer lessonType) {
        return orderDetailMapper.getTransferOrderDetail(yearPart, quarterNum, schoolId, lessonType);
    }

    /**
     * 获取学生最后一条订单数据，更新年级用
     *
     * @return
     */
    @Override
    public List<OrderDetail> getLastOrderListForStudent() {
        return orderDetailMapper.getLastOrderListForStudent();
    }


    /**
     * 更新智能课，刷题剩余课时
     *
     * @param yearPart
     * @param quarterNum
     */
    @Override
    public void updateStudentResidueCourseCount(Integer yearPart, Integer quarterNum, Long studentId) {
        QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("school_id",1600459698721300481L);
        queryWrapper.eq("year_part", yearPart);
        queryWrapper.eq("quarter_num", quarterNum);
        queryWrapper.eq("student_id", studentId);
        queryWrapper.gt("residue_course_count", 0);
        queryWrapper.ne("lesson_type", 1);//不等于精品课
        //queryWrapper.groupBy("school_id","student_id","subjects_id");
        queryWrapper.orderByAsc("school_id");
        //查找出智能课或者刷题班剩余课次大于零的数据
        List<OrderDetail> orderDetailList = this.list(queryWrapper);
        Integer i = 0;
        for (OrderDetail orderDetail : orderDetailList) {
            //获取出精品课剩余课次
            Integer residueCourseCount = this.getResidueCourseCount(orderDetail.getSchoolId(), orderDetail.getStudentId(), orderDetail.getSubjectsId(), orderDetail.getYearAndQuarter(), 1);
            residueCourseCount = residueCourseCount * 3 * 2;
            if (residueCourseCount.equals(0)) {
                orderDetail.setResidueCourseCount(0);
                this.updateById(orderDetail);
            } else {
                orderDetail.setResidueCourseCount(residueCourseCount);
                this.updateById(orderDetail);
            }
            //System.out.println(orderDetailList.size()+"---i:"+i++);
        }
    }

    @Override
    public IncomeDailyRs getIncomeDailyRsCount(Wrapper wrapper) {
        return orderDetailMapper.getIncomeDailyRsCount(wrapper);
    }

}
